package cn.newgrand.netcall;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.TimerTask;

import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;

import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.filter.OrFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.spark.ChatManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.component.RolloverButton;
import org.jivesoftware.spark.plugin.Plugin;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.ChatRoomListenerAdapter;
import org.jivesoftware.spark.ui.CommandPanel;
import org.jivesoftware.spark.ui.rooms.ChatRoomImpl;
import org.jivesoftware.spark.util.SwingTimerTask;
import org.jivesoftware.spark.util.TaskEngine;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;


import cn.newgrand.netcall.expert.transcript.TranscriptManager;
import cn.newgrand.netcall.resources.ExpertRes;
import cn.newgrand.netcall.ui.ChatTranscriptDecorator;
import cn.newgrand.netcall.ui.ExpertConfigUI;
import cn.newgrand.netcall.ui.leaveword.LeavewordPanel;
import cn.newgrand.netcall.ui.leaveword.ManagerLeavewordPanel;
import cn.newgrand.netcall.ui.questionRecord.QuestionRecordEditor;
import cn.newgrand.netcall.util.StringUtil;
import cn.newgrand.smackx.attachmenttransfer.FileTransferManager;
import cn.newgrand.smackx.specialist.ExpertManager;
import cn.newgrand.smackx.specialist.packet.LeaveWordIQ;
import cn.newgrand.smackx.specialist.packet.LeavewordInfoIQ;
import cn.newgrand.smackx.specialist.packet.NotifySaveTranscriptIQ;

public class ExpertPlugin implements Plugin,PacketListener{
	
	private final RolloverButton expertButton = new RolloverButton(ExpertRes.getImageIcon(ExpertRes.EXPERT_IMAGE));

	@Override
	public void initialize() {
		LocalPreferences preferences = SettingsManager.getLocalPreferences();
        if(!preferences.isPublicLogin()){
        	return;
        }
		OrFilter packetFilter = new OrFilter();
		packetFilter.addFilter(new PacketTypeFilter(NotifySaveTranscriptIQ.class));
		packetFilter.addFilter(new PacketTypeFilter(LeaveWordIQ.class));
		packetFilter.addFilter(new PacketTypeFilter(LeavewordInfoIQ.class));
		SparkManager.getConnection().addPacketListener(this, packetFilter);
		//发送IQ查询用户是否有专家身份
		//ExpertManager.getInstance(SparkManager.getConnection()).loadExperts(SparkManager.getSessionManager().getJID());
		boolean b = ExpertManager.getInstance(SparkManager.getConnection()).isExpert();
		if(b){
			expertButton.setToolTipText("我是专家");
	        CommandPanel cp = SparkManager.getWorkspace().getCommandPanel();
	        //cp.add(expertButton);
	        cp.add(expertButton, 0);
	        cp.validate();
	        cp.invalidate();
	        ExpertManager.getInstance(SparkManager.getConnection()).loadLeavewordInfo();
		}else{
			return;
		}
		
		SparkManager.getChatManager().addChatRoomListener(new ChatRoomListenerAdapter() {
			@Override
			public void chatRoomOpened(final ChatRoom room) {
				TimerTask task = new SwingTimerTask() {
                    public void doRun() {
                    	if (room instanceof ChatRoomImpl) {
                    		//打开房间的时候增加发送调查问卷的按钮
                            //new QuestionnaireRoomDecorator(room);
                            //打开房间的时候增加查看专家聊天记录的按钮
                            new ChatTranscriptDecorator(room);
                        }
                    }
                };

                TaskEngine.getInstance().schedule(task, 100);
			}
		});
        
        expertButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				new ExpertConfigUI(expertButton.getText()).invoke();
			}
		});
        //final FileTransferManager fileTransferManager = new FileTransferManager(SparkManager.getConnection());
        JMenuItem noteQuestionMenuItem = new JMenuItem("常见问题", SparkRes.getImageIcon(SparkRes.DOCUMENT_16x16));
        noteQuestionMenuItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				//new QuestionRecordEditor(fileTransferManager);
			}
		});
//        SparkManager.getMainWindow().getMenuByName(Res.getString("menuitem.actions")).add(noteQuestionMenuItem);
	}

	@Override
	public void shutdown() {
		SparkManager.getConnection().removePacketListener(this);
		ProviderManager.getInstance().removeIQProvider("query", "ng:iq:specialistsearch");
		ProviderManager.getInstance().removeIQProvider("query", "ng:iq:chattranscript");
		ProviderManager.getInstance().removeIQProvider("questionrecord", "ng:iq:questionrecordconfig");
		ProviderManager.getInstance().removeIQProvider("query", "ng:iq:expertvcard");
		ProviderManager.getInstance().removeIQProvider("query", "ng:iq:questionnairestatus");
		ProviderManager.getInstance().removeIQProvider("notifynextasker", "ng:iq:notifynextasker");
		ProviderManager.getInstance().removeIQProvider("query", "ng:iq:querycurrentasker");
	}

	@Override
	public boolean canShutDown() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void uninstall() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void processPacket(final Packet packet) {
		SwingUtilities.invokeLater(new Runnable() {
    		public void run() {
    			if(packet instanceof NotifySaveTranscriptIQ){
    				NotifySaveTranscriptIQ notifyIQ = (NotifySaveTranscriptIQ)packet;
    				TranscriptManager tm = new TranscriptManager();
    				String body = tm.getRoomTranscript(notifyIQ.getAskerJid(),notifyIQ.getStartTime(),notifyIQ.getOverTime());
    				if(body.length() > 0){
    					tm.saveChatTranscript2DB(notifyIQ.getAskerJid(), body, notifyIQ.getSpid());
    				}
    			}
    			if(packet instanceof LeaveWordIQ){
    				LeaveWordIQ leaveword = (LeaveWordIQ)packet;
    				String fromUser = leaveword.getFromUser();
    				String fromTrueName = leaveword.getFromTrueName();
    				//String askerJid = StringUtil.getBaseJid(fromUser);
    				LeavewordPanel leavewordPanel = ManagerLeavewordPanel.getInstance().getLeavewordPanel(fromUser);
    				if(leavewordPanel == null){
    					leavewordPanel = new LeavewordPanel(fromUser,leaveword.getSpid(),fromTrueName);
    					ManagerLeavewordPanel.getInstance().addContainerComponent(leavewordPanel);
    					//leavewordPanel.getTranscriptWindow().insertMessage(askerJid, leaveword, ChatManager.FROM_COLOR);
    					Date date = new Date(leaveword.getCreateDate());
    					leavewordPanel.getTranscriptWindow().insertHistoryMessage(fromTrueName, leaveword.getBody(), date);
    				}else{
    					//leavewordPanel.getTranscriptWindow().insertMessage(askerJid, leaveword, ChatManager.FROM_COLOR);
    					Date date = new Date(leaveword.getCreateDate());
    					leavewordPanel.getTranscriptWindow().insertHistoryMessage(fromTrueName, leaveword.getBody(), date);
    				}
    			}
    			if(packet instanceof LeavewordInfoIQ){
    				LeavewordInfoIQ leavewordInfoIQ = (LeavewordInfoIQ)packet;
    				expertButton.setText(leavewordInfoIQ.getCount());
    			}
    		}
    	});
	}

	public RolloverButton getExpertButton() {
		return expertButton;
	}
	
}
